package com.hhd.flow.engine.variable.impl;

import com.hhd.flow.engine.utils.CommonUtils;
import com.hhd.flow.engine.variable.FlowVariableDefinition;
import com.hhd.flow.engine.variable.FlowVariablesContainer;
import com.tang.script.variable.Variable;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;


public class CompositeFlowVariablesContainer implements FlowVariablesContainer {
    List<FlowVariablesContainer> containers = new LinkedList<>();

    public CompositeFlowVariablesContainer() {
    }

    public static FlowVariablesContainer forVariables(Object... args) {
        CompositeFlowVariablesContainer res = new CompositeFlowVariablesContainer();
        for (Object arg : args) {
            if (CommonUtils.isEmpty(arg)) continue;

            if (arg instanceof Collection) {
                Collection c = (Collection) arg;
                res.addAll(c);
            }
            if (arg instanceof FlowVariablesContainer) {
                res.add((FlowVariablesContainer)arg);
            }
        }
        return res;
    }

    public void add(FlowVariablesContainer flowVariablesContainer) {
        containers.add(flowVariablesContainer);
    }

    public void addAll(Collection c) {
        containers.addAll(c);
    }

    @Override
    public List<FlowVariableDefinition> getFlowVariableDefinitions() {
        List<FlowVariableDefinition> res = CommonUtils.newList();
        for (FlowVariablesContainer container : containers) {
            res.addAll(container.getFlowVariableDefinitions());
        }
        return res;
    }

    @Override
    public Object getValue(Variable variable) {
        for (FlowVariablesContainer container : containers) {
            Object value = container.getValue(variable);
            if (Objects.nonNull(value)) return value;
        }
        return null;
    }
}
